"""
给定一个包含非负整数的 m x n 网格，请找出一条从左上角到右下角的路径，使得路径上的数字总和为最小。

说明：每次只能向下或者向右移动一步。

输入:
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
输出: 7
解释: 因为路径 1→3→1→1→1 的总和最小。
"""
class Solution(object):
    def minPathSum(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        if not grid: return 0
        m, n  = len(grid), len(grid[0])
        i, j = m-1, n-1
        dp = [[0 for col in range(n)] for row in range(m)]
        while i>=0:
            while j>=0:
                if i==m-1:
                    if j == n-1:
                        dp[i][j] = grid[i][j]
                    elif j>=0:
                        dp[i][j] = dp[i][j+1] + grid[i][j]
                else:
                    if j==n-1:
                        dp[i][j] = grid[i][j] + dp[i+1][j]
                    elif j>=0:
                        dp[i][j] = min(dp[i][j+1],dp[i+1][j]) + grid[i][j]
                j -= 1
            i -= 1
            j = n-1
        print(dp[0][0])
        return dp[0][0]

s=Solution()
s.minPathSum([[1,3,1],[1,5,1],[4,2,1]])